package cn.wolfcde.luowowo.website.web.controller;

import cn.wolfcde.luowowo.website.annotation.RedisParameter;
import cn.wolfcde.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyCatalog;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.article.query.TravelQueryObject;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisticsService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisticsService;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentServiceService;
import cn.wolfcode.luowowo.common.domain.AjaxResult;
import cn.wolfcode.luowowo.common.key.RedisKey;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentServiceService travelCommentServiceService;

    @Reference
    private ITravelStatisticsService travelStatisticsService;

    @Reference
    private IStrategyStatisticsService strategyStatisticsService;

    @Reference
    private IUserInfoService userInfoService;
    @Value("${file.path}")
    private String filePath;


    /**
     * 旅游日记页面
     *
     * @return
     */
    @RequestMapping("")
    public String travel(@ModelAttribute("qo") TravelQueryObject qo, Model model) {

        //pageInfo     异步分页
        PageInfo pageInfo = travelService.queryForList(qo);
        model.addAttribute("pageInfo", pageInfo);

        //tcs
        List<TravelComment> travelComments = travelCommentServiceService.queryTop10OfTime();
        model.addAttribute("tcs", travelComments);

        //abroadCds 海外攻略排行  unabroadCds  国内攻略排行 取出所有的排行vo数据
        List<StrategyStatisVO> vo_isabroad = strategyStatisticsService.getVOsBySort(RedisKey.STRATEGY_STATIS_ISABROAD_SORT.getPrefix(), 0, -1);

        //判断是国内还是国外
        List<StrategyStatisVO> unabroadCds = new ArrayList<>();

        //分类获取国内国外的前10个vo数据
        for (StrategyStatisVO strategyStatisVO : vo_isabroad) {

            if (!strategyStatisVO.isIsabroad()) {

                if (unabroadCds.size() < 10) {

                    unabroadCds.add(strategyStatisVO);
                }
            }

        }
        //共享回页面
        model.addAttribute("unabroadCds", unabroadCds);

        return "travel/list";
    }

    /**
     * 游记详细内容页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail")
    public String travelDetail(Long id, Model model,@RedisParameter UserInfo userInfo) {

        Travel travel = travelService.get(id);
        model.addAttribute("detail", travel);

        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        model.addAttribute("toasts", toasts);

        //sds
        List<StrategyDetail> sds = strategyDetailService.getDetailsByViewTop3(travel.getDest().getId());
        model.addAttribute("sds", sds);

        //ts
        List<Travel> ts = travelService.getTravelsByViewTop3(travel.getDest().getId());
        model.addAttribute("ts", ts);

        //list
        TravelCommentQuery qo = new TravelCommentQuery();

        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);

        List<TravelComment> list = travelCommentServiceService.findByDetailId(id);

//        Page page = travelCommentServiceService.query(qo);

        model.addAttribute("list", list);

        //增加游记的阅读量
        travelStatisticsService.addViewnum(id, 1);




        //取回vo共享页面
        TravelStatisVO travelStatisVO = travelStatisticsService.getTravelStatisVO(id);

        model.addAttribute("vo", travelStatisVO);


        return "travel/detail";
    }

    /**
     * 游记添加编辑
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/input")
    public String input(Long id, Model model) {

        //dests
        List<Destination> dests = destinationService.getDestByDeep(3);
        model.addAttribute("dests", dests);

        //编辑回显的游记
        Travel t_travel = travelService.get(id);
        model.addAttribute("tv", t_travel);


        return "travel/input";

    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    /**
     * 游记编辑修改
     *
     * @param travel
     * @param model
     * @param userInfo
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(Travel travel, Model model, @RedisParameter UserInfo userInfo, Long id) {
        AjaxResult ajaxResult = new AjaxResult();

        travel.setAuthor(userInfo);

        Long tv_id = travelService.saveOrUpdate(travel);

        ajaxResult.setResult(tv_id);

        return ajaxResult;
    }

    /**
     * 添加游记评论
     *
     * @param travelComment
     * @param model
     * @param userInfo
     * @param floor
     * @return
     */
    @RequestMapping("/commentAdd")
    public String commentAdd(TravelComment travelComment, Model model, @RedisParameter UserInfo userInfo, Long floor) {

        //设置评论者信息
        if (userInfo != null) {

            travelComment.setUserId(userInfo.getId());

            travelComment.setUsername(userInfo.getNickname());

            travelComment.setCity(userInfo.getCity());

            travelComment.setLevel(userInfo.getLevel());

            travelComment.setHeadUrl(userInfo.getHeadImgUrl());

        }

        travelComment = travelCommentServiceService.save(travelComment);


        //这个楼层设计里有问题
        model.addAttribute("floor", floor + 1);

        model.addAttribute("c", travelComment);


        return "travel/commentTpl";
    }

    /**
     * 获取指定游记的内容
     *
     * @param id
     * @return
     */
    @RequestMapping("/getContent")
    @ResponseBody
    public AjaxResult getContent(Long id) {

        AjaxResult ajaxResult = new AjaxResult();

        Travel travel = travelService.get(id);

        ajaxResult.setResult(travel.getTravelContent().getContent());

        return ajaxResult;
    }

    /**
     * 收藏
     *
     * @return
     */
    @RequestMapping("/favor")
    @ResponseBody
    public AjaxResult favor(Long tid, @RedisParameter UserInfo userInfo) {

        AjaxResult ajaxResult = new AjaxResult();

        if (userInfo == null) {

            ajaxResult.setCode(102);

            ajaxResult.mark("请登录后再进行收藏");

            return ajaxResult;
        }

        Boolean result = travelStatisticsService.favor(tid, userInfo.getId());

        //获取到评论数 页面要的是vo对象
        TravelStatisVO travelStatisVO = travelStatisticsService.getTravelStatisVO(tid);

        ajaxResult.setSuccess(result);

        ajaxResult.setResult(travelStatisVO);

        return ajaxResult;
    }


    /**
     * 点赞
     *
     * @return
     */
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public AjaxResult travelThumbup(Long tid, @RedisParameter UserInfo userInfo) {

        AjaxResult ajaxResult = new AjaxResult();

        if (userInfo == null) {

            ajaxResult.setCode(102);

            ajaxResult.mark("请登录后再点赞");

            return ajaxResult;
        }

        boolean result = travelStatisticsService.travelThumbup(tid, userInfo.getId());

        ajaxResult.setSuccess(result);

        //获取到评论数 页面要的是vo对象
        TravelStatisVO travelStatisVO = travelStatisticsService.getTravelStatisVO(tid);

        ajaxResult.setResult(travelStatisVO);

        return ajaxResult;
    }


    /**
     * 分享数+1
     *
     * @param tid
     * @return
     */
    @RequestMapping("/shareAdd")
    @ResponseBody
    public AjaxResult shareAdd(Long tid) {

        AjaxResult ajaxResult = new AjaxResult();

        //分享+1
        boolean flag = travelStatisticsService.shareAdd(tid);

        if (flag) {

            //获取到评论数 页面要的是vo对象
            ajaxResult.setResult(travelStatisticsService.getTravelStatisVO(tid));

        }

        ajaxResult.setSuccess(flag);

        return ajaxResult;

    }

}
